package com.goudan.practice.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多线程交替打印 1~100
 * Lock实现
 */
public class ThreadPrint4 {

    private static int cnt = 0;

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition c1 = lock.newCondition();
        Condition c2 = lock.newCondition();
        Condition c3 = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                while (cnt <= 100 && cnt % 3 == 0) {
                    System.out.println(Thread.currentThread().getName() + "---->" + cnt);
                    cnt++;
                    c2.signal();
                    c1.await();
                }
                c3.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "T1").start();

        new Thread(() -> {
            lock.lock();
            try {
                while (cnt <= 100 && cnt % 3 == 1) {
                    System.out.println(Thread.currentThread().getName() + "---->" + cnt);
                    cnt++;
                    c3.signal();
                    c2.await();
                }
                c1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "T2").start();

        new Thread(() -> {
            lock.lock();
            try {
                while (cnt <= 100 && cnt % 3 == 2) {
                    System.out.println(Thread.currentThread().getName() + "---->" + cnt);
                    cnt++;
                    c1.signal();
                    c3.await();
                }
                c2.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "T3").start();

    }
}
